package cn.otrue.patienthealthmanager.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.DensityUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.utils.SendImageToServer;
import cn.otrue.patienthealthmanager.view.CopyOfAscertainPopupWindow;
import cn.otrue.patienthealthmanager.view.CopyOfbirthdaPopupWindow;
import cn.otrue.patienthealthmanager.view.GetPickResultListener;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 个人中心->个人信息->编辑页面
 * 
 * @author G
 * 
 */
public class CenterInfoChangeActivity extends BaseActivity {
	private Button btn_centerinfo_queren;
	private EditText et_wanxianxingming;
	private RadioGroup rp_rp;

	private EditText et_wanshanshouji;
	private EditText et_wanshandguhua;
	private EditText et_wanshanbingqing;
	private TextView tv_nian;
	private TextView tv_yue;
	private TextView tv_ri;

	private TextView et_center_in;
	private EditText et_center_fo;
	private EditText et_center_xi;
	private TextView tv_catt_city;
	private TextView tv_catt_province;
	private TextView tv_catt_town;
	private TextView tv_catt_pickCity;
	private TextView tv_catt_shi;
	private TextView tv_catt_xian;
	private View mainView;
	private String nian;
	private String yue;
	private String ri;
	private String dateStr;
	private final int TOP = 14;
	public static String name;

	public void ImageSet(String imgurl, ImageView img_headPhoto) {

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.iv_user_photo)
				.showImageOnFail(R.drawable.iv_user_photo)
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(
						new RoundedBitmapDisplayer(DensityUtil.dip2px(
								CenterInfoChangeActivity.this, 40))).build();
		ImageLoader.getInstance().displayImage(imgurl, img_headPhoto, options);
	}

	private static CopyOfAscertainPopupWindow windoww;
	Handler handler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			if (state.equals("001")) {
				if (CenterInfoActivity.centerinfos != null) {
					CenterInfoActivity.centerinfos.finish();
				}
				Intent mianIntent = new Intent(CenterInfoChangeActivity.this,
						CenterInfoActivity.class);
				startActivity(mianIntent);
				finish();
			} else {
				Toast.makeText(getApplicationContext(), msg, 0).show();
			}
		}

		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			// super.onFail(data);

		}

	};
	private CopyOfbirthdaPopupWindow windowwi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_center_infochange);
		initView();

	}

	private void getData() {
		isComplete = getIntent().getIntExtra("isComplete", -1);
		realname = getIntent().getStringExtra("Realname");
		if (realname != null) {
			et_wanxianxingming.setText(realname);
		}
		dateStr = birthday = getIntent().getStringExtra("Birthday");

		if (birthday != null) {
			String[] dateArr = dateStr.split("-");
			tv_nian.setText(dateArr[0] + "年");
			tv_yue.setText(dateArr[1] + "月");
			tv_ri.setText(dateArr[2] + "日");
		}
		nickName = getIntent().getStringExtra("NickName");
		if (nickName != null) {
			et_wanshandguhua.setText(nickName);
		}

		mobile = getIntent().getStringExtra("Mobile");
		if (mobile != null) {
			et_wanshanshouji.setText(mobile);
		}

		diseasehistory = getIntent().getStringExtra("Diseasehistory");
		if (diseasehistory != null) {
			et_wanshanbingqing.setText(diseasehistory);
		}

		sex = getIntent().getStringExtra("Sex");
		if (sex != null) {

		}
		address = getIntent().getStringExtra("Address");
		if (address != null) {
			String[] dateA = address.split("-");
			et_xiangqing.setText(dateA[3]);
			tv_catt_pickCity.setText(dateA[0]);
			tv_catt_shi.setText(dateA[1]);
			tv_catt_xian.setText(dateA[2]);
		}

		headimg = getIntent().getStringExtra("Headimg");
		if (headimg != null) {
			ImageSet(headimg, pe_head_image);
		}

	}

	private void initView() {

		pe_head_image = (ImageView) findViewById(R.id.pe_head_image);
		pe_head_image.setOnClickListener(listener);
		mainView = findViewById(R.id.ll_pick);
		findViewById(R.id.rl_catt_pickCity).setOnClickListener(this);
		btn_centerinfo_queren = (Button) findViewById(R.id.btn_centerinfo_queren);
		btn_centerinfo_queren.setOnClickListener(this);
		et_wanxianxingming = (EditText) findViewById(R.id.et_wanxianxingming);
		et_wanxianxingming.setOnClickListener(this);
		rp_rp = (RadioGroup) findViewById(R.id.rp_rp);
		et_xiangqing = (EditText) findViewById(R.id.et_xiangqing);
		et_wanshanshouji = (EditText) findViewById(R.id.et_wanshanshouji);
		et_wanshanshouji.setOnClickListener(this);
		et_wanshandguhua = (EditText) findViewById(R.id.et_wanshandguhua);
		et_wanshandguhua.setOnClickListener(this);
		et_wanshanbingqing = (EditText) findViewById(R.id.et_wanshanbingqing);
		et_wanshanbingqing.setOnClickListener(this);
		tv_nian = (TextView) findViewById(R.id.tv_nian);
		tv_nian.setOnClickListener(this);
		tv_yue = (TextView) findViewById(R.id.tv_yue);
		tv_yue.setOnClickListener(this);
		tv_ri = (TextView) findViewById(R.id.tv_ri);
		tv_ri.setOnClickListener(this);
		tv_catt_pickCity = (TextView) findViewById(R.id.tv_catt_pickCity);
		tv_catt_pickCity.setOnClickListener(this);
		tv_catt_shi = (TextView) findViewById(R.id.tv_catt_shi);
		tv_catt_shi.setOnClickListener(this);
		tv_catt_xian = (TextView) findViewById(R.id.tv_catt_xian);
		tv_catt_xian.setOnClickListener(this);
		getData();
		initTitleBar();
	}

	class MyPickResultListener implements GetPickResultListener {

		@Override
		public void onGetResult(Object[] results, int type) {
			if (type == 1) {
				nian = (String) results[0];
				tv_catt_pickCity.setText(nian);
				yue = (String) results[1];
				tv_catt_shi.setText(yue);
				ri = (String) results[2];
				tv_catt_xian.setText(ri);
			} else if (type == 2) {
				dateStr = results[0].toString();
				String[] dateArr = dateStr.split("-");
				tv_nian.setText(dateArr[0] + "年");
				tv_yue.setText(dateArr[1] + "月");
				tv_ri.setText(dateArr[2] + "日");

			}
		}
	}

	/**
	 * 初始化头部titlebar
	 */
	public void initTitleBar() {
		TextView tv_title_title = (TextView) findViewById(R.id.tv_title_title);
		TextView tv_title_back = (TextView) findViewById(R.id.tv_title_back);
		tv_title_ot = (TextView) findViewById(R.id.tv_title_other);
		tv_title_ot.setText(getString(R.string.tiaoguo));
		tv_title_title.setText(getString(R.string.centerinfo_change));

		tv_title_back.setVisibility(View.VISIBLE);
		if (isComplete == 0) {
			tv_title_ot.setVisibility(View.VISIBLE);
		} else {

		}
		tv_title_ot.setOnClickListener(this);

		tv_title_back.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.btn_centerinfo_queren:
			if (TextUtils.isEmpty(et_wanxianxingming.getText().toString())) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.xingming), 0).show();
			} else if (TextUtils.isEmpty(et_wanshanshouji.getText().toString())) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.shouji), 0).show();
			} else if (et_wanshanshouji.getText().toString().length() != 11) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.shoujion), 0).show();
			} else if (TextUtils.isEmpty(tv_nian.getText().toString())) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.shengri), 0).show();
			} else if (TextUtils.isEmpty(tv_catt_pickCity.getText().toString())) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.zhuzhi), 0).show();
			} else if (TextUtils.isEmpty(et_wanshandguhua.getText().toString())) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.guhua), 0).show();
			} else if (TextUtils.isEmpty(et_wanshanbingqing.getText()
					.toString())) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.bingli), 0).show();
			} else {

				if (pathabsolute != null) {
					SendImageToServer send = new SendImageToServer(
							pathabsolute, this);
					send.startThread();
				} else {
					setMemberData();

				}

			}
			break;
		case R.id.tv_title_back:
			if (isComplete == 0) {
				Intent mianIntent = new Intent(CenterInfoChangeActivity.this,
						LoginActivity.class);

				startActivity(mianIntent);
				finish();
			} else {
				finish();
			}
		case R.id.tv_title_ot:
			finish();

			break;
		case R.id.tv_catt_pickCity:
			windoww = new CopyOfAscertainPopupWindow(this,
					new MyPickResultListener());
			windoww.setBackgroundDrawable(new BitmapDrawable());
			windoww.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.tv_catt_shi:
			windoww = new CopyOfAscertainPopupWindow(this,
					new MyPickResultListener());
			windoww.setBackgroundDrawable(new BitmapDrawable());
			windoww.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.tv_catt_xian:
			windoww = new CopyOfAscertainPopupWindow(this,
					new MyPickResultListener());
			windoww.setBackgroundDrawable(new BitmapDrawable());
			windoww.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;

		case R.id.tv_nian:

			windowwi = new CopyOfbirthdaPopupWindow(this,
					new MyPickResultListener());
			windowwi.setBackgroundDrawable(new BitmapDrawable());
			windowwi.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;
		case R.id.tv_yue:

			windowwi = new CopyOfbirthdaPopupWindow(this,
					new MyPickResultListener());
			windowwi.setBackgroundDrawable(new BitmapDrawable());
			windowwi.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;
		case R.id.tv_ri:

			windowwi = new CopyOfbirthdaPopupWindow(this,

			new MyPickResultListener());
			windowwi.setBackgroundDrawable(new BitmapDrawable());
			windowwi.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;

		}

	}

	public void setMemberData() {
		SharedPreferences shared = getSharedPreferences("tupian",
				this.MODE_PRIVATE);
		String userhead = null;
		if (name != null) {
			userhead = name;
		} else {
			userhead = shared.getString("memhead", "");
		}
		HashMap map = new HashMap<String, Object>();
		map.put("realname", et_wanxianxingming.getText().toString());
		if (rp_rp.getCheckedRadioButtonId() == R.id.radioButton1) {
			map.put("sex", "1");
		} else {
			map.put("sex", "0");
		}
		map.put("nickName", et_wanshandguhua.getText().toString());
		map.put("headimg", userhead);
		map.put("mobile", et_wanshanshouji.getText().toString());
		map.put("birthday", dateStr);

		if (nian == null) {
			String[] dateA = address.split("-");
			String juti = dateA[3];
			String sheng = dateA[0];
			String shi = dateA[1];
			String xian = dateA[2];
			map.put("address", sheng + "-" + shi + "-" + xian + "-" + juti);
		} else {
			map.put("address", nian + "-" + yue + "-" + ri + "-"
					+ et_xiangqing.getText().toString());
		}

		map.put("diseasehistory", et_wanshanbingqing.getText().toString());
		map.put("aliasAccount", MyConst.getACCOUNT());
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername("");
		parameter.setPassword(" ");
		parameter.setData(map);
		new HttpServer().post(HttpCons.update_Patient_Baseinfo, parameter,
				handler);

	}

	private View.OnClickListener listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.pe_head_image:
				AlertDialog.Builder builder = new AlertDialog.Builder(
						CenterInfoChangeActivity.this);
				builder.setTitle("选择头像");
				builder.setPositiveButton("从本地上传", dialoglistener);
				builder.setNegativeButton("拍照上传", dialoglistener);
				builder.create();
				builder.show();
				break;

			default:
				break;
			}
		}

	};
	private final int IMAGEREQUESTCODE = 1;
	private final int PHOTOREQUESTCODE = 2;
	private DialogInterface.OnClickListener dialoglistener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				Intent imageIntent = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(imageIntent, IMAGEREQUESTCODE);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(photoIntent, PHOTOREQUESTCODE);
				break;
			}
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1 && resultCode == Activity.RESULT_OK
				&& data != null) {
			Uri uri = data.getData();
			Cursor cursor = getContentResolver().query(uri, null, null, null,
					null);// 获取系统数据：所有系统内保存的数据都可以通过
			cursor.moveToFirst();
			String imagePath = cursor.getString(1);
			cursor.close();
			Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
			Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight());
			bitmap = getRoundedCornerBitmap(getResources(), bitmap);
			saveBitmap(bitmap);
			pe_head_image.setImageBitmap(bitmap);
		}
		if (requestCode == 2 && resultCode == Activity.RESULT_OK
				&& data != null) {
			Bundle bundle = data.getExtras();
			Bitmap bitmap = (Bitmap) bundle.get("data");
			// 缩放画圆
			bitmap = getRoundedCornerBitmap(getResources(), bitmap);
			saveBitmap(bitmap);
			pe_head_image.setImageBitmap(bitmap);
		}
	};

	private String pathabsolute;
	public static CenterInfoChangeActivity activity;
	private EditText et_jianjie;
	private EditText et_yiyuan;
	private String realname;
	private String birthday;
	private String nickName;
	private String mobile;
	private String diseasehistory;
	private String sex;
	private String address;
	private ImageView pe_head_image;
	private String headimg;
	private EditText et_xiangqing;
	private int isComplete;
	private TextView tv_title_ot;

	/**
	 * 将一张图片修改为圆形图片
	 * 
	 * @param res
	 *            资源对象
	 * @param bitmap
	 *            要修改的位图
	 * @return 修改成功后的位图，结果是正方法形
	 * @author BGX
	 * @time 2015-4-26
	 */
	public static Bitmap getRoundedCornerBitmap(Resources res, Bitmap bitmap) {
		Bitmap load = BitmapFactory.decodeResource(res,
				R.drawable.iv_user_photo);
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		if (width > height) {
			width = height;
		} else {
			height = width;
		}
		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, width, height);
		final RectF rectF = new RectF(rect);
		final float roundPx = width > height ? height / 2 : width / 2;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		output = zoomImage(output, load.getWidth(), load.getHeight());
		return output;
	}

	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	/**
	 * 用于保存圆形图片
	 * 
	 * @param bitmap
	 *            要保存的图片
	 * @return 是否保存成功
	 */
	public boolean saveBitmap(Bitmap bitmap) {
		boolean success = false;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File sdcardPath = Environment.getExternalStorageDirectory();// 获取sd卡目录
			File dir = new File(sdcardPath, "imagefile");// 在该目录下创建文件
			if (!dir.exists()) {
				dir.mkdirs();
			}
			Date date = new Date();// 时间要用util包
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = dateFormat.format(date) + ".jpg";
			File file = new File(dir, fileName);
			try {
				bitmap = getRoundedCornerBitmap(getResources(), bitmap);
				success = bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
						new FileOutputStream(file));
				// 路径保存
				pathabsolute = file.getAbsolutePath();
				SharedPreferences share = getSharedPreferences("imagefile",
						CenterInfoChangeActivity.this.MODE_PRIVATE);
				Editor edit = share.edit();
				edit.putString("path", pathabsolute);
				edit.commit();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			Toast.makeText(this, "sdk不可用", Toast.LENGTH_LONG).show();
		}
		if (success == true) {
			// Toast.makeText(this, "头像设置成功", Toast.LENGTH_LONG).show();
			return true;
		}
		return false;
	}
}
